package com.css.fxfzypg.modules.baseData.repository.impl;


import com.alibaba.fastjson.JSONObject;
import com.css.fxfzypg.constants.FxfzConstants;
import com.css.fxfzypg.constants.YNEnum;
import com.css.fxfzypg.modules.baseData.dto.PeoDTO;
import com.css.fxfzypg.modules.baseData.queryParams.PeoQueryParams;
import com.css.fxfzypg.modules.baseData.repository.PeoRepository;
import com.css.fxfzypg.modules.baseData.entity.PeoEntity;
import com.css.fxfzypg.util.CreateGson;
import com.css.fxfzypg.util.PlatformObjectUtils;
import com.css.fxfzypg.web.PlatformSessionContext;
import com.css.fxfzypg.zcpt.sys.entity.SUser;
import com.css.fxfzypg.zcpt.sys.service.SUserService;
import com.css.fxfzypg.zcpt.sys.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author y1fan
 * @create 2022-08-11 14:57
 */
@Repository
public class PeoRepositoryImpl implements PeoRepository {
    @Autowired
    SysRoleService sysRoleService;

    @Autowired
    SUserService sUserService;

    @Resource
    private JdbcTemplate jdbcTemplate;
    @Resource
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    @Override
    public PeoEntity findPeoById(String dataPeoId) {
        String sql = "";
        sql = "select * from data_peo where data_peo_id='" + dataPeoId + "'";
        PeoEntity peoEntity = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(PeoEntity.class));
        return peoEntity;
    }

    @Override
    public void updatePeo(PeoDTO peoDTO) {
        String sql = "update data_peo set peo_total = :peoTotal ,peo_avg_house = :peoAvgHouse ,peo_avg_area = :peoAvgArea" +
                " ,update_user = :updateUser ,update_time = :updateTime where data_peo_id = :dataPeoId";
        SqlParameterSource source = new BeanPropertySqlParameterSource(peoDTO);
        namedParameterJdbcTemplate.update(sql, source);
    }

    @Override
    public Map<String, Object> getAllPeoByParams(PeoQueryParams queryParams, int curPage, int pageSize) {
        StringBuilder sql = new StringBuilder("select * from data_peo");
        StringBuilder whereSql = new StringBuilder(" where is_delete = '0' ");
//        StringBuilder orderSql = new StringBuilder(" order by province_code,city_code,prefecture_code ");
        StringBuilder orderSql = new StringBuilder();
        if ("0".equals(queryParams.getOption())) {
            orderSql.append(" order by province_code,city_code,prefecture_code asc");
        }
        if ("1".equals(queryParams.getOption())) {
            orderSql.append(" order by COALESCE (update_time,create_time) desc ");
        }
        if ("2".equals(queryParams.getOption())) {
            if ("0".equals(queryParams.getOption1())) {
                orderSql.append("order by CAST(peo_total AS DECIMAL) asc ");
            }
            if ("1".equals(queryParams.getOption1())) {
                orderSql.append("order by CAST(peo_total AS DECIMAL) desc nulls last");
            }
        }
        if ("3".equals(queryParams.getOption())) {
            if ("0".equals(queryParams.getOption1())) {
                orderSql.append("order by peo_avg_house asc");
            }
            if ("1".equals(queryParams.getOption1())) {
                orderSql.append("order by peo_avg_house desc nulls last");
            }
        }
        if ("4".equals(queryParams.getOption())) {
            if ("0".equals(queryParams.getOption1())) {
                orderSql.append("order by peo_avg_area asc");
            }
            if ("1".equals(queryParams.getOption1())) {
                orderSql.append("order by peo_avg_area desc nulls last");
            }
        }
        int firstIndex = (curPage - 1) * pageSize;
        int lastIndex = pageSize;

        StringBuilder str = new StringBuilder("");
        String userId = PlatformSessionContext.getUserID();
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        String role = sysRoleService.getRoleByUserId(userId);
        List<Map> roleMaps = JSONObject.parseArray(role, Map.class);
        for (Map roleMap : roleMaps) {
            str.append(roleMap.get("roleCode") + ",");
        }
        String roles = str.toString();
        if (roles.contains(FxfzConstants.YPG_PRI_YW_ROLE) || roles.contains(FxfzConstants.YPG_PRI_GL_ROLE) && !roles.contains(FxfzConstants.YPG_COUN_GL_ROLE) && !roles.contains(FxfzConstants.YPG_COUN_YW_ROLE)) {
            whereSql.append(" and province_id = '" + sUser.getProvinceId() + "'");
        }

        StringBuilder limitSql = new StringBuilder(" limit " + lastIndex + " offset " + firstIndex);
        if (!PlatformObjectUtils.isEmpty(queryParams.getProvinceId())) {
            whereSql.append(" and province_id = '" + queryParams.getProvinceId() + "'");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getCityId())) {
            whereSql.append(" and city_id = '" + queryParams.getCityId() + "'");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getPrefectureId())) {
            whereSql.append(" and prefecture_id = '" + queryParams.getPrefectureId() + "'");
        }
        sql.append(whereSql).append(orderSql);
        Integer total = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(PeoEntity.class)).size();
        List<PeoEntity> list = jdbcTemplate.query(sql.append(limitSql).toString(), new BeanPropertyRowMapper<>(PeoEntity.class));
        Map<String, Object> map = new HashMap();
        map.put("total", total);
        map.put("rows", list);
        return map;
    }

    @Override
    public void deletePeo(List<String> list) {
        String sql = "update data_peo set is_delete = '" + YNEnum.Y.toString() + "' where data_peo_id in (:ids)";
        Map map = new HashMap();
        map.put("ids", list);
        namedParameterJdbcTemplate.update(sql, map);
    }

    @Override
    public PeoEntity findPeoByProAndCityAndPre(String province, String city, String prefecture) {
        String sql =
                "select * from data_peo where province = '" + province + "' and city = '" + city + "' and prefecture = '" + prefecture + "' and is_delete = '" + YNEnum.N.toString() + "' ";
        try {
            PeoEntity peoEntity = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(PeoEntity.class));
            return peoEntity;
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
    }

    @Override
    public void importExcel(PeoEntity peoEntity) {
        String sql = "update data_peo set peo_total = :peoTotal ,peo_avg_house = :peoAvgHouse ,peo_avg_area = :peoAvgArea ,update_user = :updateUser ,update_time = :updateTime where data_peo_id = :dataPeoId";
        SqlParameterSource source = new BeanPropertySqlParameterSource(peoEntity);
        namedParameterJdbcTemplate.update(sql, source);
    }

    @Override
    public void save(PeoEntity peoEntity1) {
        String sql = "insert into data_peo values(:dataPeoId, :province, :city, :prefecture, :peoTotal, :peoAvgHouse, " +
                ":peoAvgArea, :updateTime, :isDelete, :provinceId, :cityId, :prefectureId, :updateUser, :createUser, :createTime,:provinceCode, :cityCode, :prefectureCode)";
        SqlParameterSource source = new BeanPropertySqlParameterSource(peoEntity1);
        namedParameterJdbcTemplate.update(sql, source);
    }

    @Override
    public Integer countByCounty(String province, String city, String county) {
        return jdbcTemplate.queryForObject("SELECT count(*) from data_peo where prefecture = '" + county + "' and city = '" + city + "' and province = '" + province + "' and is_delete ='0'  and (peo_total is not null or peo_avg_house is not null  or peo_avg_area is not null)  ", Integer.class);
    }

    @Override
    public Integer countByCity(String province, String city) {
        return jdbcTemplate.queryForObject("SELECT count(*) from data_peo where city = '" + city + "' and province = '" + province + "' and is_delete ='0'", Integer.class);
    }

    @Override
    public Integer countByProvince(String province) {
        return jdbcTemplate.queryForObject("SELECT count(*) from data_peo where province = '" + province + "' and is_delete ='0' ", Integer.class);
    }

    @Override
    public Integer countByProvinceAndYear(String provinceName, String taskYear) {
        return jdbcTemplate.queryForObject("SELECT count(*) from data_peo where province = ? and (TO_CHAR(update_time, 'yyyy-MM-dd hh24:mi:ss') LIKE ? or TO_CHAR(create_time, 'yyyy-MM-dd hh24:mi:ss') LIKE ?) and is_delete ='0'", Integer.class, provinceName, taskYear + "%", taskYear + "%");
    }
}
